package com.example.paypallesson01.config;

import com.paypal.base.rest.APIContext;
import com.paypal.base.rest.OAuthTokenCredential;
import com.paypal.base.rest.PayPalRESTException;
import com.paypal.core.PayPalEnvironment;
import com.paypal.core.PayPalHttpClient;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: anlu
 * @Date: 2021/06/28
 * @Description:
 */
@Configuration
@Slf4j
@Data
public class PaypalConfig {
    @Value("${paypal.client.app}")
    private String clientId;
    @Value("${paypal.client.secret}")
    private String clientSecret;
    @Value("${paypal.mode}")
    private String mode;

    @Value("${paypal.webscr}")
    private String webscr;
    @Value("${natapp.domain}")
    private String domain;

    /**
     * IPN异步验证返回
     */
    public static final String PAYMENT_IPN_VERIFIED = "VERIFIED";
    public static final String PAYMENT_IPN_COMPLETED_STATUS = "COMPLETED_STATUS";
    public static final String PAYMENT_IPN_REFUNDED_STATUS = "REFUNDED_STATUS";
    public static final String PAYMENT_IPN_INVALID = "INVALID";

    /**
     * IPN异步通知返回通知消息类型
     */
    public static final String PAYMENT_STATUS_PENDING = "PENDING";
    public static final String PAYMENT_STATUS_VOIDED = "VOIDED ";
    public static final String PAYMENT_STATUS_COMPLETED = "COMPLETED ";
    public static final String PAYMENT_STATUS_REFUNDED = "REFUNDED ";


    @Bean
    public Map<String, String> paypalSdkConfig(){
        Map<String, String> sdkConfig = new HashMap<>();
        sdkConfig.put("mode", mode);
        return sdkConfig;
    }

    @Bean
    public OAuthTokenCredential authTokenCredential(){
        return new OAuthTokenCredential(clientId, clientSecret, paypalSdkConfig());
    }

    /**
     * V1版本的apiContext
     */
    @Bean
    public APIContext apiContext() throws PayPalRESTException {
        APIContext apiContext = new APIContext(authTokenCredential().getAccessToken());
        apiContext.setConfigurationMap(paypalSdkConfig());
        return apiContext;
    }

    /**
     * V2 版本的客户端
     */
    public PayPalHttpClient client() {
        PayPalEnvironment environment = mode.equals("live") ? new PayPalEnvironment.Live(clientId, clientSecret) : new PayPalEnvironment.Sandbox(clientId, clientSecret);
        return new PayPalHttpClient(environment);
    }

}
